
#include "audPinIn.h"
#include "..\..\include\imp_typedefine.h"
#include "..\..\include\imp_io_wrapper.h"

static int gSize = 0;

CMiiAudPinIn::CMiiAudPinIn(CBaseFilter *pFilter, HRESULT *phr) : CBaseInputPin(NAME("CAudioPinIn"), pFilter, this, phr, L"MiiShow_Audio_input")
, m_bCopy(false)
, m_nSourcIndex(0)
{
	ZeroMemory(&m_tType, sizeof(m_tType));
	mOutMax  = 2048;
	for(int i=0; i<BUF_NUM; i++){
		m_pBuffer[i] = new char[mOutMax];
		m_lock[i] = CreateEvent( NULL, FALSE, TRUE, NULL );
	}
	m_nBufIndex = 0;
	m_Pos = 0;
}

CMiiAudPinIn::~CMiiAudPinIn()
{
	for(int i=0; i<BUF_NUM; i++){
		delete []m_pBuffer[i];
		CloseHandle(m_lock[i]);
	}
}

HRESULT CMiiAudPinIn::CompleteConnect(IPin *pReceivePin)
{
	return S_OK;
}

HRESULT CMiiAudPinIn::SetMediaType(const CMediaType *pmt)
{
	WAVEFORMATEX  * pvih;
	if(pmt->pbFormat){
		pvih = (WAVEFORMATEX *)pmt->pbFormat;
		memcpy(&m_vInfo, pvih, sizeof(m_vInfo));
	}
	return S_OK;
}

HRESULT CMiiAudPinIn::CheckConnect(IPin *)
{
	return S_OK;
}

HRESULT CMiiAudPinIn::CheckMediaType(const CMediaType *pmt)
{
	GUID* subtype = (GUID*)pmt->Subtype();
	if(*subtype == MEDIASUBTYPE_PCM)
		return S_OK;
	/*if(*subtype == MEDIASUBTYPE_WAVE)
		return S_OK;*/
	return S_FALSE;
}

HRESULT CMiiAudPinIn::GetMediaType(int iPosition, CMediaType *pMediaType)
{
	if (iPosition < 0)
	{
		return E_INVALIDARG;
	}

	if (!m_tType.IsValid())
	{
		return VFW_S_NO_MORE_ITEMS;
	}
	
	if (iPosition > 0)
	{
		return VFW_S_NO_MORE_ITEMS;
	}

	if (pMediaType)
	{
		CopyMediaType(pMediaType, &m_tType);
	}

	return S_OK;
}

CMediaType *CMiiAudPinIn::MediaType()
{
	return &m_mt;
}

extern void miidx_input_audio(Int8 *pBuffer, UInt32 pts, Int32 size, Int32 sample_rate, Int32 ch, Int32 sb);

STDMETHODIMP CMiiAudPinIn::Receive(IMediaSample *pSample)
{
	HRESULT hr;
	char *pBuffer;
	int nLength;
	LONGLONG tstart, tend;
	WAVEFORMATEX  * pvih = 0;
	AM_MEDIA_TYPE  *pmt = 0;
		
	CheckPointer(pSample,E_POINTER);
	if(S_OK == pSample->GetMediaType(&pmt))
	{
		if(pmt->pbFormat){
			pvih = (WAVEFORMATEX *)pmt->pbFormat;
			memcpy(&m_vInfo, pvih, sizeof(m_vInfo));
		}
	}

	hr = pSample->GetPointer((BYTE **)&pBuffer);
	nLength = pSample->GetActualDataLength();

	hr = pSample->GetTime(&tstart, &tend);

	if(hr==S_OK)
	{
		mTimeStamp = tstart/10000;
		miidx_input_audio(pBuffer, mTimeStamp, nLength, m_vInfo.nSamplesPerSec, m_vInfo.nChannels, m_vInfo.wBitsPerSample);
		//Sleep(tend/10000-mTimeStamp);
	}
	return S_OK;
}

STDMETHODIMP CMiiAudPinIn::EndOfStream(void)
{
	return S_OK;
}
